package com.hsylient.javase.chapter09;

import com.hsylient.javase.common.enmu.Status;
import com.hsylient.javase.common.entity.Employee;
import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class TestListToMap {

    public static void main(String[] args) {
        // 准备原始的数据集合
        List<Employee> employees = List.of(
                new Employee(1L, "A", 12, 123.45, Status.FREE),
                new Employee(1L, "A", 13, 666.45, Status.FREE),
                new Employee(1L, "C", 14, 123.45, Status.FREE),
                new Employee(1L, "D", 15, 123.45, Status.FREE),
                new Employee(1L, "E", 16, 123.45, Status.FREE),
                new Employee(1L, "F", 17, 123.45, Status.FREE),
                new Employee(1L, "G", 18, 123.45, Status.FREE));


        // 将list转为map(当有两个Employee的name一样的时候就会报错)
        Map<String, Double> nameSalary = employees.stream().collect(Collectors.toMap(Employee::getName, Employee::getSalary));
        System.out.println(nameSalary);

        // 这个方法提供了key冲突的解决方案，这个时候他会给一个value的解决方案，existingValue：代表同名key的老值，newValue：代表同名key的新值
        Map<String, Double> collect = employees.stream().collect(Collectors.toMap(Employee::getName, Employee::getSalary, (existingValue, newValue) -> newValue));
        System.out.println(collect);

        // 这个方法在解决key冲突的情况下，可以将list转换到指定类型的Map中，比如：LinkedHashMap ConcurrentHashMap等
        LinkedHashMap<String, Integer> linkedHashMap = employees.stream().collect(Collectors.toMap(Employee::getName, Employee::getAge, Integer::sum, LinkedHashMap::new));
        System.out.println(linkedHashMap);
    }
}
